package com.buka.user.controller;

import com.buka.user.entity.User;
import com.buka.user.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/saveUser")
public class SaveUserServlet extends HttpServlet {

    UserService userService = new UserService();

    //做修改信息功能时
    // 1.我们要先通过ID查询到原始数据
    // 2.将传递过来的值赋给第一步查到的对象

    /***
     *  原因：
     *      对象中属性很多，有些时候修改方法只是修改个别几个属性
     *      例如user对象有  name/age/addr/phone/email/passed/sex
     *      1.只想修改  email
     *          如果写sql   update user set email=？ where id = ？
     *      2.修改手机号
     *          update user set phoneNo=？ where id = ？
     *
     *      为了减少重复开发工作
     *          update user set email = 'sdsdsd', phoneNo='源记录的phoneNo' where id=？
     *
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String id = req.getParameter("id");
        String userName = req.getParameter("userName");
        String phoneNo = req.getParameter("phoneNo");
        String email = req.getParameter("email");
        String passwd = req.getParameter("passwd");
        //调用service 查询用户信息 执行update 方法
        User user = userService.selectById(id);
        //当前查询的用户信息改为新值
        user.setId(Long.valueOf(id));
        user.setUserName(userName);
        user.setPhoneNo(phoneNo);
        user.setEmail(email);
        user.setPasswd(passwd);

        int update = userService.update(user);
        if (update > 0) {
            resp.sendRedirect("index.html");

        }else{
            req.getRequestDispatcher("WEB-INF/error.jsp").forward(req, resp);
        }


    }
}
